//
//  YYYNetworkManager+Extension.swift
//  HotNews
//
//  Created by YYY on 2017/9/29.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import Foundation

// MARK: 封装新浪微博的网络请求方法
extension YYYNetworkManager
{
    /// 微博首页列表数据
    ///
    /// - Parameters:
    ///   - since_id: 下拉刷新使用
    ///   - max_id: 上拉加载使用
    ///   - completion: 完成回调
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping(_ result: [[String: Any]]?, _ isSuccess: Bool)->())
    {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //let params = ["access_token": "2.00gk1fkDjuT3IC2cacdea2136dJVEC"]
        let params = ["since_id": "\(since_id)",
                      "max_id": "\(max_id)"]
        
        tokenRequest(urlString: urlString, parameters: params) { (json, success) in
            
            let tempJson = json as? [String: Any]
            
            let arrayDict = tempJson?["statuses"] as? [[String: Any]]
            
            completion(arrayDict, success)
        }
    }
    
    //未读的微博数据
    func unreadStatusData(completion: @escaping(_ count: Int)->())
    {
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        tokenRequest(urlString: urlString, parameters: params) { (json, isSuccess) in
            
            let dict = json as? [String: Any]
            let unreadCount = dict?["status"] as? Int ?? 0
            completion(unreadCount)
        }
    }
    
    //发布微博
    func postStatus(text: String, image: UIImage?, completion: @escaping(_ result: [String: AnyObject]?, _ isSuccess: Bool)->())
    {
        var name: String?
        var data: Data?
        
        let urlString: String
        if image == nil
        {
            //发布纯文本微博
            urlString = "https://api.weibo.com/2/statuses/update.json"
        }
        else
        {
            //发布带图片的微博
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            name = "pic"
            data = UIImagePNGRepresentation(image!)
        }
        let params = ["status": text]
        
        //拼接token
        tokenRequest(method: .POST, urlString: urlString, parameters: params, name: name, data: data) { (json, isSuccess) in
            
            let dict = json as? [String: AnyObject]
            completion(dict, isSuccess)
        }
    }
    
}

extension YYYNetworkManager
{
    /// 获取用户授权
    /// - Parameters:
    ///   - code: 授权码
    ///   - complection: 完成回调
    func loadOAUth(code: String, complection: @escaping(_ isSuccess: Bool)->())
    {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": SinaAppKey,
                      "client_secret": SinaAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": SinaAppRedirect_uri]
        loadRequest(method: .POST, urlString: urlString, parameters: params) { (json, isSuccess) in
            let dict = json as? [String: Any] ?? [:]
            //使用yy_modelSet将json字典转换成YYYUserAccount模型
            //用户模型中数据值保存在内存中
            self.userAccount.yy_modelSet(with: dict)
        
            //加载用户信息数据
            self.loadUserInfo(completion: { (result) in
                self.userAccount.yy_modelSet(with: result)
                //保存用户模型数据
                self.userAccount.saveAccount()
                complection(isSuccess)
            })
        }
    }
    //加载用户信息
    func loadUserInfo(completion: @escaping(_ dict: [String: Any])->())
    {
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid": uid] as [String: Any]
        tokenRequest(urlString: urlString, parameters: params) { (json, isSuccess) in
            let dict = (json as? [String: Any]) ?? [:]
            completion(dict)
        }
    }
}
